/*
1.加载登录界面
2.用户账号密码
3.有可能同意，有可能取消，判断
4.加载accesstoken


*/

import UIKit
import SVProgressHUD

class ELOauthViewController: UIViewController , UIWebViewDelegate {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //读取新浪的请求页面
        let request = NSURLRequest(URL: ELNetWorkTool.shareNetWork.oauthURL())
        webView.loadRequest(request)
        
        title = "新浪微博"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "fillTheAccout")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancleLogin")
    }
    
    override func loadView() {
        view = webView
        webView.delegate = self
    }
    
    //MARK: - webview代理方法
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let URL = request.URL!.absoluteString as NSString
//        print("URL ====== \(URL)")
        
        //如果不是授权回调地址的话直接返还true 加载
        if !URL.hasPrefix(ELNetWorkTool.shareNetWork.redirect_uri) {
            return true
        }
        
        //如果是授权回调地址则判断
        //取消:回到登录界面 //{ URL: https://m.baidu.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330&from=844b&vit=fps }
        
        //授权:加载新界面 URL: http://www.baidu.com/?code=4ddec28e4bc4efff385ffb0321ead99e
        //问号后面的内容
        if let query = request.URL?.query {
            
            //如果？后面是code=则表示授权成功
            let codeStr = "code="
            if query.hasPrefix(codeStr) {
                
                //截取code的值
                let queryNS = query as NSString
                let code = queryNS.substringFromIndex(codeStr.characters.count)
                print("code = \(code)")
                
                //发送accesstoken请求
                loadAccessToken(code)
                
            }else {
                //否则取消 关闭页面
                cancleLogin()
            }

        }
        
        //是回调地址则不加载
        return false
    }
    
    private func loadAccessToken (code : String) {
        ELNetWorkTool.shareNetWork.loadAccessTocken(code) { (result, error) -> () in
            
            if error != nil {
                print(error)
                print("你的网络不给力")
                
                self.cancleLogin()
                return
            }
            //没有错误则保存用户数据
           let uesrAccount = ELUserAccount.init(dict: result!)
            //保存到沙盒
            uesrAccount.saveUserAccount()
            
//            print("uesrAccount = \(uesrAccount)")
            //切换控制去到主页面
            UIApplication.sharedApplication().keyWindow?.rootViewController = ELNewFeatureController()
            //关闭加载
            self.cancleLogin()
        }
    }
    
    ///开始加载网页
    func webViewDidStartLoad(webView: UIWebView) {
        
        SVProgressHUD.showWithStatus("玩命加载中", maskType: SVProgressHUDMaskType.Black)
    }
    
    ///加载网页结束
    func webViewDidFinishLoad(webView: UIWebView) {
        
        SVProgressHUD.dismiss()
    }
    
    //MARK: - 私有方法
    ///填充用户名和密码
    @objc private func fillTheAccout () {
        
        let js = "document.getElementById('userId').value='jiwangb24744@sina.com'; document.getElementById('passwd').value='987426b24744';"
        // 让webView执行js代码
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
    
    ///取消登录操作
    @objc private func cancleLogin () {
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //MARK: - 懒加载
    private lazy var webView = UIWebView()
}
